package com.jinandi.app.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.ModelMap;

import com.jinandi.app.domain.User;
import com.jinandi.app.service.UserService;

/**
 * <抽象父类Controller 代码复用>
 * 
 * @author CGC
 * @version [记录版本号, 2013-4-17]
 */
public abstract class BaseController {
	
	@Autowired
	private UserService userService;

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	/**
	 * <获取当前用户>
	 * @return
	 * @author CGC 
	 * 创建日期:2013-4-17 上午10:58:23
	 */
	protected User getCurrentUser() {
		User u = userService.getCurrentUser();
		User user = userService.findUserById(u.getId());
		return user;
	}
	

	/**
	 * <格式化json数据>
	 * @param modelMap
	 * @param page
	 * @return
	 * @author CGC 
	 * 创建日期:2013-4-18 下午4:38:07
	 */
	@SuppressWarnings("rawtypes")
	protected ModelMap getFormatJsonForJtable(ModelMap modelMap,Page page){
		modelMap.addAttribute("Result", "OK");
		modelMap.addAttribute("TotalRecordCount", page.getTotalElements());
		modelMap.addAttribute("Records", page.getContent());
		return modelMap;
	}
	
	/**
	 * <错误信息>
	 * @param modelMap
	 * @param message
	 * @return
	 * @author CGC 
	 * 创建日期:2013-5-14 下午2:18:58
	 */
	protected ModelMap getErrorJson(ModelMap modelMap,String message){
		modelMap.addAttribute("Result", "ERROR");
		modelMap.addAttribute("Message", message);
		return modelMap;
	}

	/**
	 * <封装下从Request获取的参数>
	 * 
	 * @param params
	 * @return
	 * @author CGC 创建日期:2013-4-16 下午3:54:31
	 */
	protected final Map<String, String> getStrictParams(
			Map<String, String[]> params) {
		Map<String, String> strictParams = new HashMap<String, String>();
		Set<Entry<String, String[]>> set = params.entrySet();
		for (Entry<String, String[]> entry : set) {
			String value = ((String[]) entry.getValue())[0];
			if ((value != null) && (!value.trim().equals(""))) {
				strictParams.put(entry.getKey(), value);
			}
		}
		return strictParams;
	}
}
